<template>
	<Toolbar
		style="border-bottom: 1px solid #ccc; width: 100%;"
		:editor="editorRef"
		:defaultConfig="toolbarConfig"
		mode="default"
	/>
	<textarea ref="editorTextarea" id="editorTextarea" style="display: none;"></textarea>
	<Editor
		style="overflow-y: hidden; border: 1px #333333 solid;"
		:style="{ width: width, height: height }"
		v-model="content"
		:defaultConfig="editorConfig"
		mode="default"
		@onCreated="handleCreated"
		@onChange="handleChange"
	/>
</template>

<!--
v-model: 富文本输入框绑定的值(必填)
width: 富文本输入框宽度(可选) % 或者 px
height: 富文本输入框高度(可选) % 或者 px
-->

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {ref, defineProps, defineEmits} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from 'axios'
import {ElMessage} from "element-plus";

const props = defineProps({
	width: {
		type: String,
		default: '100%'
	},
	height: {
		type: String,
		default: '500px'
	},
	modelValue: {
		type: String,
		default: ''
	}
})
const emit = defineEmits(['update:modelValue'])

const content = ref('')
const handleChange = (editor) => {
	emit('update:modelValue', editor.getHtml())
}

//富文本编辑器实例配置
const editorRef = ref(null)
const editorTextarea = ref(null)
const toolbarConfig = {}
const editorConfig = {
	placeholder: '请输入内容...',
	textarea: '#editorTextarea',
	MENU_CONF: {
		uploadImage: {
			customUpload: async (file, insertFn) => {
				try {
					const formData = new FormData()
					formData.append('file', file)
					// 使用 axios 发送上传请求
					const response = await axios.post('/api/hzadmin/public/upload_image/', formData, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					});

					// 成功处理
					const imageUrl = response.data;
					insertFn(`/api/${imageUrl}`);
				} catch (error) {
					// 错误处理
					let errorMessage = '图片上传失败：未知错误';
					if (error.response) {
						errorMessage = `图片上传失败：${error.response.data.msg || '接口返回错误'}`;
					} else if (error.request) {
						errorMessage = '图片上传失败：请求未得到响应';
					} else {
						errorMessage = `图片上传失败：${error.message}`;
					}
					ElMessage.error(errorMessage);
				}
			}
		}
	}
}
const handleCreated = (editor) => {
	editorRef.value = editor // 记录 editor 实例，重要！
}
</script>
<style scoped lang="scss">

</style>
